#coding=utf-8
from django.db import connection


def GetList():
	ReturnInfo={}
	cur=connection.cursor()
	sql="select parentname,name,id from budget_itemlist order by parentname"
	cur.execute(sql)
	result=cur.fetchall()
	cur.close()
	tmpname=''
	for oneline in result:
		if oneline[0]<>tmpname:
			ReturnInfo[oneline[0]]=[]
			tmpname=oneline[0]
		ReturnInfo[oneline[0]].append([oneline[1],oneline[2]])
	return ReturnInfo
	
def GetItemInfo():
	cur=connection.cursor()
	cur.execute("call sp_GetItemInfo()")
	result=cur.fetchall()
	cur.close()
	return result
	
def GetPicInfo():
	cur=connection.cursor()
	cur.execute("call sp_GetParentItem()")
	result=cur.fetchall()
	cur.close()
	PicInfo=''
	for name,price in result:
		PicInfo=PicInfo+'%s\t%s\n'%(name,price)
	PicInfo=PicInfo[:-1]
	return PicInfo
	
def GetItemDetail(itemid):
	cur=connection.cursor()
	cur.execute("select id,itemname,price,num,priceall,satisfaction,brand,market,otherinfo from budget_iteminfo where itemid=%s"%itemid)
	result=cur.fetchall()
	cur.execute("select concat(parentname,'&nbsp->&nbsp',name) from budget_itemlist where id=%s"%itemid)
	itemname=cur.fetchone()[0]
	cur.close()
	return itemname,result
	
def GetOneItmeInfo(idx):
	cur=connection.cursor()
	cur.execute("select id,itemname,price,num,priceall,satisfaction,brand,market,otherinfo,itemid from budget_iteminfo where id=%s"%idx)
	result=cur.fetchone()
	cur.close()
	OneItemInfo={
	  'idx':result[0],
	  'itemname':result[1],
	  'price':result[2],
	  'num':result[3],
	  'priceall':result[4],
	  'satisfaction':result[5],
	  'brand':result[6],
	  'market':result[7],
	  'otherinfo':result[8],
	  'itemid':result[9]
	}
	return OneItemInfo
	
def ModifyItemInfo(OneItemInfo):
	cur=connection.cursor()
	if OneItemInfo['price']==None:
		OneItemInfo['price']=0
	if OneItemInfo['priceall']==None:
		OneItemInfo['priceall']='null'
	sql="call sp_ModifyItemInfo(%s,%s,'%s',%s,%s,%s,%s,'%s','%s','%s')"%(OneItemInfo['idx'],OneItemInfo['itemid'],OneItemInfo['itemname'].encode('utf-8'),OneItemInfo['price'],OneItemInfo['num'],OneItemInfo['priceall'],OneItemInfo['satisfaction'].encode('utf-8'),OneItemInfo['brand'].encode('utf-8'),OneItemInfo['market'].encode('utf-8'),OneItemInfo['otherinfo'].encode('utf-8'))
	cur.execute(sql)
	cur.execute("commit")
	cur.close()
	
def DelItemInfo(idx):
	cur=connection.cursor()
	sql="delete from budget_iteminfo where id=%s"%idx
	cur.execute(sql)
	cur.execute("commit")
	cur.close()
	
def GetRGF(itemid):
	cur=connection.cursor()
	cur.execute("call getRGF(%s)"%(itemid))
	result=cur.fetchall()
	cur.close()
	return result
	
def ModifyRGF(initidx,realnum):
	cur=connection.cursor()
	cur.execute("update budget_rgf set realnum=%s where id=%s"%(realnum,initidx))
	cur.execute("commit")
	cur.close()